package cn.yi.newsys.dao.impl;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import cn.yi.newsys.dao.NewsCategoryDao;
import cn.yi.newsys.pojo.NewsCategory;
import cn.yi.newsys.utils.BaseDao;

public class NewsCategoryDaoImpl extends BaseDao implements NewsCategoryDao{

	@Override
	public List<NewsCategory> getAllNewsCategory() {
		String sql = "SELECT tid,tname FROM news_category " ;
		NewsCategory nc = null ;
		List<NewsCategory> list = new ArrayList<NewsCategory>() ;
		ResultSet rs = this.executeQuery(sql, null) ;
		try {
			while(rs.next()){
				
				nc = new NewsCategory() ;
				nc.setId(rs.getInt("tid")) ;
				nc.setName(rs.getString("tname"));
				list.add(nc) ;
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return list ;
	}

	@Override
	public NewsCategory getNewsCategoryByID(int id) {
		NewsCategory nc = null ;
		String sql = "SELECT tname FROM news_category WHERE tid=?" ;
		Object objs [] = new Object[]{id} ;
		ResultSet rs = this.executeQuery(sql, objs) ;
		try {
			if(rs.next()){
				nc = new NewsCategory() ;
				nc.setId(id) ;
				nc.setName(rs.getString("tname")) ;
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return nc ;
	}

	@Override
	public NewsCategory getNewsCategoryByName(String name) {
		NewsCategory nc = null ;
		String sql = "SELECT tid FROM news_category WHERE tname=?" ;
		Object objs [] = new Object[]{name} ;
		ResultSet rs = this.executeQuery(sql, objs) ;
		try {
			if(rs.next()){
				nc = new NewsCategory() ;
				nc.setId(rs.getInt("tid")) ;
				nc.setName(name) ;
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return nc ;
	}

	@Override
	public int addNewsCategory(NewsCategory nc) {
		int row = 0 ;
		String sql = "INSERT INTO news_category(tname) VALUES(?)" ;
		Object objs [] = new Object []{nc.getName()} ;
		try{
			row = this.executeUpdate(sql, objs) ;
		}finally{
			this.close();
		}
		return row ;
	}

}
